<template>
  <div class="v-charts" ref="chartRef"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts/core'
import { useCharts, chartsResize } from './useCharts'
import { PropType, toRefs, shallowRef, onMounted, watch, nextTick } from 'vue'

const props = defineProps({
  // 主题配置
  theme: String,
  // 监听图表设置是否变化
  isWatch: [String, Boolean, Object],
  // 图表数据配置
  options: {
    type: Object as PropType<echarts.EChartsCoreOption>,
    default: () => ({})
  },
})

// 接收使用者传递的参数
const { theme, options } = toRefs(props)

// 获取dom
const chartRef = shallowRef()

const { charts, setOptions, initChart } = useCharts({ theme, el: chartRef, options })

// 开启默认放大缩放功能
const turnOndataZoom = () => {
  charts.value.dispatchAction({
    type: 'takeGlobalCursor',
    key: 'dataZoomSelect',
    dataZoomSelectActive: true
  })
}

onMounted(async () => {
  await initChart()
  setOptions(options.value)
})

// 传入数据发生变化， 刷新图表
watch(
  options,
  () => {
    setOptions(options.value)
    nextTick(() => turnOndataZoom())
  },
  {
    deep: true
  }
)


// 是否开启外部左侧菜单引起的布局适配问题
watch(
  () => props.isWatch,
  () => {
    chartsResize.handleResize()
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  chartRef: chartRef,
  $charts: charts
})
</script>

<script lang="ts">
export default { name: "v-charts" };
</script>

<style lang="scss" scoped>
.v-charts {
  width: 100%;
  height: 100%;
  clear: both;
  // min-height: 240px;
}
</style>
